<template>
	<view class="_form_item_container" :class="{ 'blink-background': errorMessage }" :style="customerStyle">
		<view class="_form_item_label">
			<view class="_sign" v-if="validateFlag">*</view>
			{{ props.label }}
		</view>
		<slot></slot>
		<view class="msg" v-if="errorMessage">{{ errorMessage }}</view>
	</view>
</template>

<script setup>
	import {
		computed,
		ref,
		inject,
		onMounted
	} from "vue";

	const props = defineProps({
		label: {
			type: String,
			default: "",
		},
		labelPosition: {
			type: String,
			default: "top",
		},
		type: {
			type: String,
			default: "name",
		},
		prop: {
			type: String,
			default: "DEFAULT",
		},
	});
	let validateFlag = ref(false);
	let errorMessage = ref("");
	const customerStyle = computed(() => {
		return {
			"flex-direction": props.labelPosition === "top" ? "column" : "row",
			"background-color": errorMessage.value === "" ? "none" : "#fde7e9",
		};
	});

	// 注入父组件的注册方法
	const registerFormItem = inject("registerFormItem");

	//是否具有表单验证功能
	const haveValidate = inject("haveValidate");

	function validate(msg) {
		errorMessage.value = msg;
		setTimeout(() => {
			errorMessage.value = "";
		}, 2000);
	}

	// 在组件挂载时注册自己
	onMounted(() => {
		registerFormItem(props.prop, {
			validate,
		});
		validateFlag.value = haveValidate(props.prop)
	});

	defineExpose({
		validate,
	});
</script>

<style scoped lang="scss">
	._form_item_container {
		width: 100%;
		display: flex;
		flex-direction: column;
		gap: 10rpx;
		border-radius: 20rpx;
		padding: 10rpx;
	}

	._form_item_label {
		font-size: 1rem;
		flex: 0 0 auto;
		font-weight: bold;
		display: flex;
		align-items: center;
		position: relative;
	}

	._sign {
		color: red;
		position: absolute;
		left: -20rpx;
	}

	.msg {
		color: red;
	}

	// 定义背景色闪烁的动画
	@keyframes blink {
		0% {
			background-color: #fde7e9;
		}

		50% {
			background-color: rgba(253, 231, 233, 0.5);
		}

		100% {
			background-color: #fde7e9;
		}
	}

	// 应用动画的类
	.blink-background {
		animation: blink 0.5s infinite;
	}
</style>